package servlet;

import com.geepi.base.DBUtil;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public class DelCollectionServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("doGet start...");
		request.setCharacterEncoding("UTF-8");
		String account = request.getParameter("account");
		String resourceId = request.getParameter("resourceId");
		String delSql = String.format("DELETE FROM favorites WHERE account = '%s' and resourceId = '%s';", account, resourceId);
		
		int status = -1;
		String message = "";
		DBUtil dbUtil = new DBUtil();
		boolean isOpen = dbUtil.open();
		if (isOpen == false) {
			status = 102;
			message = "数据库打开失败";
		} else {
			boolean isDelSuccess = dbUtil.update(delSql);
			if (isDelSuccess) {
				status = 0;
				message = "取消收藏成功";
			} else {
				status = 100002;
				message = "取消收藏失败";
			}
		}
		
		Map<String, Object> tempParamsMap = new HashMap<String, Object>();
		tempParamsMap.put("status", status);
		tempParamsMap.put("msg", message);
		JSONObject jsonObject = null;		
		jsonObject = JSONObject.fromObject(tempParamsMap);


		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.println(jsonObject);
		out.flush(); // 必须有这行，不然页面不会显示
		out.close();

		System.out.println("doGet end...");
		super.doGet(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(req, resp);
		super.doPost(req, resp);
	}

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	

}
